package offer;


import java.util.LinkedList;
import java.util.Queue;



/**
 * @Author SSK
 * @Date Created in 12:04 2019/8/8
 * @Description 序列化二叉树
 * @Version 1.0
 */
public class T62 {
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;

        }

        @Override
        public String toString() {
            return super.toString()+val;
        }
    }
    String Serialize(TreeNode root) {
        if (root==null) {
            return "#";
        }
        StringBuilder stringBuilder = new StringBuilder();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node !=root) {
                stringBuilder.append(",");
            }
            if (node==null) {
                stringBuilder.append("#");
            }else {
                stringBuilder.append(""+node.val);
                queue.add(node.left);
                queue.add(node.right);
            }
        }
        return stringBuilder.toString();
    }
    TreeNode Deserialize(String str) {
        if (str.charAt(0)=='#') {
            return null;
        }
        String[] strs = str.split(",");
        TreeNode root = new TreeNode(Integer.parseInt(strs[0]));
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        for (int i = 1; i < strs.length; i+=2) {
             TreeNode node = queue.poll();
             if (strs[i].charAt(0)!='#') {
                 node.left = new TreeNode(Integer.parseInt(strs[i]));
                 queue.add(node.left);
             }
             if (strs[i+1].charAt(0)!='#') {
                 node.right = new TreeNode(Integer.parseInt(strs[i+1]));
                 queue.add(node.right);
             }
        }
        return root;
    }
    public void test() {
        String s = "8,6,10,5,7,9,11";
        System.out.println(Serialize(Deserialize(s)));
    }
    public static void main ( String[] args) {
        new T62().test();

    }
}
